/**
 * Newtouch Bairn JS Library 0.1
 * 
 * Depands on jQuery.js and newtouch-common.js
 * Copyright(c) 2009 Newtouch
 * 
 * xiaohua.ding@newtouch.cn
 *
 * 本文件中所有的以'_'符号开头的方法被认为是private的方法或属性，不对外部公开的。
 * 如果外部使用了以'_'符号开头的方法或属性，一旦出现问题将由使用者自己解决。
 */

Newtouch.message = {
	
	onLoad:function(){
		//TODO dosoming before load
	},
	offLoad:function(){
		//TODO dosoming after load
	},
	
	/**
	 * validate  
	 * 默认css依赖 newtouch-common.css 
	 */
	_error:'error',
	_fine:'fine',
	
	/**
	 * 输入框的验证信息
	 * @param input 验证的输入控件jQuery对象
	 * @param message 验证后显示的信息
	 * @param error 验证是否正确[true/false]
	 */
	validate:function(input,message,error){
	
		var msg = "";
		
		if(error){
		
			msg = this._errorHTML(input,message,this._error);
			input.addClass(this._error);
			
		}else{
		
			msg = this._errorHTML(input,message,this._fine);
			input.removeClass(this._error);
		}
		
		input.parent().find("span." + this._error + " label").replaceWith(msg);
	},
	
	_errorHTML:function(input,message,cls){
	
		var msgHTML = "<label class='" + cls + "' " + " generated='true' " + " for='" + input.attr("id") + "'> " + message + "</label>";
		return msgHTML;
	},
	
	showMsg:function(msg,sucess){
		alert(msg);
	}
};

Newtouch.Util = {

	/**
	 * 处理URI使之不带'?'和'#'及任何参数
	 * 如果URI带有'#'在ie下会导致不能提交请求
	 *
	 */
	helperUrl:function(url){
  		var index = url.indexOf("?");
  
	  	if(index>0){
	   		return url.substring(0,index);
	  	}
	  
	  	var indexSharp = url.indexOf("#");
	  
	  	if(indexSharp>0){
	   		return url.substring(0,indexSharp);
	  	}
	  
	  	return url;
 	},

	/**
	 * 在action中也可以带上url的形式如下
	 * requiredpage.jsp.actionname
	 */
	helperAction:function(action){
		var point = action.lastIndexOf(".");
		if(point >= 0){
			var url = action.substring(0,point);
			var _action = action.substring(point+1,action.length);
			return {
				url:url,
				action:_action
			}
		}else{
			var url = this.helperUrl(document.URL);
			return {
				url:url,
				action:action
			}
		}
	},
	
	/**
	 * 把action作为参数放入到参数列表中。
	 */
	helperParams:function(params,action){
		if(typeof(params) == "string"){
			params = this._stringParams(params,action);
		}else{
			params['_action'] = action;
		}
		
		return params;
	},
	/**
	 * 处理返回值中的回车换行符号(\n\r)
	 * @param data 返回的responseText
	 * @param replacestr 把\n\r替换为指定的字符，默认为<br/>
	 */
	helperResponse:function(data,replacestr){
		if(typeof(data)=="object"){
			return data;
		}
		if(replacestr == undefined){
			replacestr = "<br/>";
		}
		
		while(data.indexOf("\n\r")>0){
			data = data.replace("\n\r",replacestr);
		}
	
		while(data.indexOf("\n")>0){
			data = data.replace("\n",replacestr);
		}
		while(data.indexOf("\r")>0){
			data = data.replace("\r",replacestr);
		}
		if(data.indexOf("\\")>0){
			data = data.replace(/\\/g,"\\\\");
		}
		return data;
	},
	
	/**
	 * 处理导出的参数只能为String类型。
	 */
	helperExportParams:function(params,action){
		return this._stringParams(params,action);
	},
	
	_stringParams:function(params,action){
	
		if(typeof(params) == "string"){
		
			if(params == ""){
			params = "_action="+action;
			}else{
				params += "&_action=" + action;
			}
			
		}else if(typeof(params) == "object"){
			for(var name in params){
				params += name + "=" + params[name] + "&";
			}
			
			params += "_action="+action;
		}
		
		return params;
		
	},
	stringToObject:function(string){
		if(string == null || string.length == 0){
			return {};
		}
		var stringArray = string.split("&");
		var stringObject = new Object();
		for(var i = 0 ;i < stringArray.length ; i++){
			var kv = stringArray[i].split("=");
			if(kv.length == 1){
				continue;
			}
			stringObject[kv[0]]=kv[1];   
		}
		return stringObject;
	}
	
};

Newtouch.Ajax = {

	_requestObject:function(url,params,successCallback,failCallback,syncCall){
		return {
			async: (syncCall != null && syncCall)? false: true,
			url:url,
			data:params,
			type:'POST',
			contentType:'application/x-www-form-urlencoded; charset=utf-8',
			success:function(data){
			
				data = Newtouch.Util.helperResponse(data);
				
				var response = null;
				if(data == ""){
					response = {err:null,result:null};
				}else{
					try{
						response = eval("(" + data + ")");
					}catch(e){
						if(failCallback){
							failCallback("访问超时，请刷新页面重新登录！");
							return;
						}else{
							alert("访问超时，请刷新页面重新登录！");
							return;
						}
					}
				}
				if(response.err == null){
					successCallback(response.result);
				}else{
					failCallback(response.err);
				}
			}
		};
	},
	/**
	 * 通过FORMID发送请求
	 * @param formId  FORM表单ID
	 * @param action  后台方法名
	 */
	sendForm:function(formId,action,successCallback,failCallback,syncCall){
	
		var ac = Newtouch.Util.helperAction(action);
		var params = $("#" + formId).formSerialize() + "&_action=" + ac.action;
		
		$.ajax(this._requestObject(ac.url,params,successCallback,failCallback,syncCall));
				
	},
	/**
	 * 通过Params发送请求
	 * @param valueMap  页面上的值 格式："{id:id,name:name}"
	 * @param action  后台方法名
	 */
	sendParams:function(valueMap,action,successCallback,failCallback,syncCall){
		
		var ac = Newtouch.Util.helperAction(action);
		var params = Newtouch.Util.helperParams(valueMap,ac.action);
		
		$.ajax(this._requestObject(ac.url,params,successCallback,failCallback,syncCall));
	}

};

Newtouch.Direct = {

	/**
	 * 导出用的方法。
	 * 手动添加参数
	 */
	sendParamsExport:function(params,action){
	
		var ac = Newtouch.Util.helperAction(action);
		var urlParams = Newtouch.Util.helperExportParams(params,ac.action);
		
		location.href = ac.url + "?" + urlParams;
	},
	
	/**
	 * 导出用的方法，通过form ID传入参数。
	 */
	sendFormExport:function(formId,action){
	
		var ac = Newtouch.Util.helperAction(action);
		var params = Newtouch.Util.helperParams($("#" + formId).formSerialize(),ac.action);
		
		location.href = ac.url + "?" + params;
	},
	/**
	 * 直接把数据当做form表单传递。
	 */
	postDataWithForm : function(action,params){
		
		var divElem = document.createElement("div");
		$(divElem).css("display","none");
		
		var form = document.createElement("form");
		
		form.method = "post";
		form.action = action;
		
		for(var p in params){
			var input = document.createElement("input");
			$(input).attr("name",p);
			$(input).attr("value",params[p]);
			form.appendChild(input);
		}
		
		$(divElem).append($(form));
		$("body").append($(divElem));
		
		form.submit();
	},
	/**
	 * 直接把数据当做form表单传递。
	 */
	postDataWithWizardForm : function(action,params){
		
		var divElem = document.createElement("div");
		$(divElem).css("display","none");
		
		var form = document.createElement("form");
		
		form.method = "post";
		form.action = action;
		
		var wizardParams = "&";
		
		for(var p in params){
			var input = document.createElement("input");
			$(input).attr("name",p);
			$(input).attr("value",params[p]);
			
			wizardParams += (p +"=" + params[p] + "&");
			form.appendChild(input);
		}
		
		var wizardInput = document.createElement("input");
		$(wizardInput).attr("name","_wzv");
		$(wizardInput).attr("value",wizardParams);
		form.appendChild(wizardInput);
		
		$(divElem).append($(form));
		$("body").append($(divElem));
		
		form.submit();
	}
};


